'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview VIP特权礼包列表
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var dataApi = require('../../../../libs/dataApi');
var vipShopConf = require('../../../../config/vipShopConf');
var PlayerManager = require('../../../../libs/playerManager');
var Code = require('../../../../consts/code');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var shop_list = [];
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'shop', 'vip', 'accrued'], cb);
            },
            function (cb) {
                var role_model = player_manager.role;
                var vip_model = player_manager.vip;
                var job_type = role_model.getJob();
                var vip_lv = role_model.getVip();
                var now_shop_id = job_type * 100 + (+vip_lv + 1);
                var shop_conf = vipShopConf.getVipPrivilegeShopConf(now_shop_id) || [];
                var vip_shop_list = dataApi.vip_privilege_shop.all();

                _.each(vip_shop_list, function (value, key) {
                    if (parseInt((+key) / 100) === job_type) {
                        var state = 0;

                        // 是否已购买过
                        if (!vip_model.isVipPrivilegeBuyList(+key)) {
                            state = 1;
                        }

                        var bit = parseInt(+key % 100 - 1);

                        // vip等级没有达到
                        if (bit > vip_lv) {
                            state = 2;
                        }

                        shop_list.push({
                            ID: +key,
                            state: state
                        });
                    }
                });

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    shop_list: shop_list
                }
            });
        }
    );
};
